package com.quan.web.controller.weixin;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.quan.common.annotation.RequiresPermissions;
import com.quan.common.base.pojo.JSONResult;
import com.quan.common.base.pojo.PageBean;
import com.quan.common.core.support.BaseController;
import com.quan.sdk.weixin.model.Message;
import com.quan.sdk.weixin.tools.MessageTools;
import com.quan.weixin.rpc.api.WeixinTextService;
import com.quan.weixin.rpc.model.WeixinText;

@RestController
@RequestMapping(value = "/api/weixin/message")
public class WeixinMessageController extends BaseController {
	
	@Autowired
	private WeixinTextService weixinTextService;

	
	@RequiresPermissions(value="weixin:text:add", description="添加微信群发消息")
	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody Message message, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return JSONResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
		}
		
		String touser = message.getTouser() ;
		if(StringUtils.isBlank(touser)) {
			return JSONResult.failure("群发用户不能为空");
		}
		String[] userSplit = touser.split(",") ;
		if(message.isSendType()) {
			if(userSplit.length < 2) {
				return JSONResult.failure("群发用户不能小于2个用户");
			}
			JSONObject jsonObject = MessageTools.send(message, MessageTools.SendType.NORMAL) ;
			
			if(jsonObject.getInteger("errcode") == 0) {
				return JSONResult.ok("群发发送成功");
			} else {
				return JSONResult.failure(jsonObject.toJSONString());
			}
			
		} else {//发送预览
			if(userSplit.length > 1) {
				return JSONResult.failure("预览群发用户只能一个");
			}
			JSONObject jsonObject = MessageTools.send(message, MessageTools.SendType.PREVIEW) ;
			
			if(jsonObject.getInteger("errcode") == 0) {
				return JSONResult.ok("预览群发发送成功");
			} else {
				return JSONResult.failure(jsonObject.toJSONString());
			}
		}
	}

	@RequiresPermissions(value="weixin:text:delete", description="删除微信群发消息")
	@GetMapping(value = "/delete/{id}")
	public Object delete(@PathVariable Integer id) {
		this.weixinTextService.deleteById(Integer.valueOf(id.toString()));
		return JSONResult.ok();
	}
	
	@RequiresPermissions(value="weixin:text:delete", description="删除微信群发消息")
	@GetMapping(value = "/deleteBatch")
	public Object deleteBatch(String ids) {
		this.weixinTextService.deleteByIds(ids) ;
		return JSONResult.ok();
	}

	@RequiresPermissions(value="weixin:text:update", description="修改微信群发消息")
	@PostMapping(value = "/update")
	public Object update(@Valid @RequestBody WeixinText entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return JSONResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		this.weixinTextService.update(entity);
		return JSONResult.ok();
	}

	@RequiresPermissions(value="weixin:text:detail", description="查询微信群发消息详情")
	@GetMapping(value = "/get/{id}")
	public Object list(@PathVariable Integer id) {
		return this.weixinTextService.selectOneById(id);
	}
	
	@RequiresPermissions(value="weixin:text:list", description="查询微信群发消息")
	@GetMapping(value = "/list")
	public Object list(WeixinText entity) {
		return this.weixinTextService.selectPage(entity, new PageBean(request)) ;
	}
	
	/**
	 * 群发消息
	 * @param vo
	 * @return
	 */
	/*private JSONObject messageSend(MessageSendVo vo) {
		return send(vo, API.MESSAGE_SEND_URL) ;
	}*/
	
	/**
	 * 群发预览消息
	 * @param vo
	 * @return
	 */
	/*private JSONObject messageSendPreview(MessageSendVo vo) {
		return send(vo, API.PREVIEW_MESSAGE_SEND_URL) ;
	}
	
	private JSONObject send(MessageSendVo vo, String sendUrl) {
		logger.debug("消息类型：{}", vo.getMsgtype());
		logger.debug("群发列表：{}", vo.getTouser());
		
		String url = API.get(sendUrl, WeixinContext.getAccessToken());
		
		Map<String, Object> map = new HashMap<String, Object>() ;
		List<String> toUserList = Arrays.asList(vo.getTouser().split(","));
		
		map.put("touser", vo.isSendType() ? toUserList : vo.getTouser()) ;
		map.put("msgtype", vo.getMsgtype());
		
		if(vo.getMsgtype().equals(MessageSendType.mpnews.getValue())) {//图文消息
			
		} else if(vo.getMsgtype().equals(MessageSendType.text.getValue())) {//文本消息
			Map<String, Object> content = new HashMap<String, Object>() ;
			content.put("content", vo.getContent()) ;
			map.put("text", content);
			
		} else if(vo.getMsgtype().equals(MessageSendType.voice.getValue())) {//语音消息
			
		} else if(vo.getMsgtype().equals(MessageSendType.image.getValue())) {//图片消息
			
		} else if(vo.getMsgtype().equals(MessageSendType.mpvideo.getValue())) {//视频消息
			
		} else if(vo.getMsgtype().equals(MessageSendType.wxcard.getValue())) {//卡券
			
		}
		
		//使用这个发送才不会乱码
		String string = HttpClientUtil.post(url, JSON.toJSONString(map), null);
		return JSON.parseObject(string);
	}*/
	
}
